<template>
	<div class="addGoodBox">
		<u-popup v-model="visiable" mode="right">
			<view>
				<view class="top">
					<view class="top-tit">添加商品</view>
					<image @click="close" class="close-btn"
						src="https://www.yongshantuan.cn/images/yongshan/arrowHui.png" mode=""></image>
				</view>
				<view class="content">
					<view class="list">
						<view class="title">商品名称</view>
						<view class="inputContent"><u-input type="text" v-model="goodInfo.foodName"
								placeholder="请输入商品名称"></u-input></view>
					</view>
					<!-- <view class="list switchList">
						<view class="title">必选项:</view>
						<view class=""><u-switch v-model="goodInfo.isLimitSelect" activeColor="#FA690A" @change="switchChange"></u-switch></view>
					</view> -->
					<view class="list">
						<view class="title">商品描述</view>
						<view class="inputContent"><u-input type="text" v-model="goodInfo.foodDescription"
								placeholder="请填写商品描述"></u-input></view>
					</view>
					<view class="list">
						<view class="title">商品图上传</view>
						<view class="addImg" @click="goToCropper">
							<image src="https://www.yongshantuan.cn/images/yongshan/platformSide/addImg.png"
								v-if="!goodInfo.foodPic" mode="aspectFill"></image>
							<image :src="goodInfo.foodPic" mode="" v-if="goodInfo.foodPic"></image>
						</view>
					</view>
					<view class="list">
						<view class="title spec">
							<view class="">
								<view style="margin-right: 10px;">启用规格</view>
								<u-checkbox @change="radioChange" activeColor="#FA690A" shape="circle"
									v-model="goodInfo.isUseSpecifications"></u-checkbox>
							</view>
							<view class="" @click="addFirstSpec">添加一级规格</view>
						</view>
						<view class="specContent">
							<block v-for="(item, index) in goodInfo.specifications" :key="index">
								<view class="specList">
									<view class=""><u-input type="text" v-model="item.specificationName"
											:clearable="false" placeholder="一级分类名"></u-input></view>
									<view class="">
										<image src="https://www.yongshantuan.cn/images/yongshan/platformSide/add.png"
											mode="" @click="addSecoundSpec(index)"></image>
										<image src="https://www.yongshantuan.cn/images/yongshan/platformSide/del.png"
											mode="" @click="delFirstSpec(index)"></image>
									</view>
								</view>
								<block v-if="item.nextSpecifications && item.nextSpecifications.length != 0">
									<view class="specList secound"
										v-for="(childItem, childIndex) in item.nextSpecifications" :key="childIndex">
										<view class="">
											<view class=""><u-input type="text" :clearable="false"
													v-model="childItem.specificationName" placeholder="二级分类名"></u-input>
											</view>
										</view>
										<view class="">
											<image
												src="https://www.yongshantuan.cn/images/yongshan/platformSide/del.png"
												mode="" @click="delSecoundSpec(index, childIndex)"></image>
										</view>
									</view>
								</block>
							</block>
						</view>
					</view>
					<view class="list">
						<view class="title">限购</view>
						<view class="inputContent"><u-input type="text" placeholder="-1无限库存，0为无库存"
								v-model="goodInfo.limitNum"></u-input></view>
					</view>
					<view class="list" v-if="type != 'add'">
						<view class="title">选择公司：</view>
						<view class=""><u-input v-model="companyInfo.companyName" type="select" :border="true"
								placeholder="请选择公司：" @click="showSelect()" /></view>
					</view>
					<!-- <view class="list">
						<view class="title">yesno上架</view>
						<view class="stateContent">
							<view class="stateButton" @click="goodInfo.upFlag = '上架中'"
								:class="{ 'check': goodInfo.upFlag == '上架中' }">上架</view>
							<view class="stateButton" @click="goodInfo.upFlag = '下架中'"
								:class="{ 'check': goodInfo.upFlag == '下架中' }">下架</view>
						</view>
					</view> -->
					<view class="commenButton" @click="submit">保存</view>
				</view>
			</view>
		</u-popup>
		<u-toast ref="uToast"></u-toast>
		<!-- 多选框下拉 -->
		<u-action-sheet :list="companyList" v-model="selectShow" @click="selectCallBack"></u-action-sheet>
	</div>
</template>

<script>
	import {
		createGoodWithCompany,
		editGoodWithCompany
	} from '@/utils/req/api.js';
	import {
		mapActions,
		mapState,
		mapGetters,
		mapMutations
	} from 'vuex';
	export default {
		props: ['companyId'],
		data() {
			return {
				pageNo: 1,
				pageSize: 10,

				fileList: [],

				visiable: false,
				specCheck: '',
				goodInfo: {
					foodName: '',
					merchantId: uni.getStorageSync('myInfo').id, //对应门店ID
					specifications: [],
					// upFlag: '上架中',
					limitNum: '-1',
					isUseSpecifications: false
				},
				companyInfo: {},
				storeList: [],
				selectShow: false,
				from: '', //
				type: ''
			};
		},
		created() {
			uni.$on('uAvatarCropper', path => {
				console.log('this.goodInfo', this.goodInfo);
				this.$set(this.goodInfo, 'foodPic', path);
			});
		},
		computed: {
			...mapState('commonModule', ['companyList'])
		},

		methods: {
			showAlert(type, record, from) {
				this.type = type;
				this.from = from;
				console.log('record', record);
				if (type == 'edit' || type == 'copy') {
					this.goodInfo = record;
					this.goodInfo.isUseSpecifications = this.goodInfo.isUseSpecifications == 'yes' ? true : false;
					this.goodInfo.specifications = this.goodInfo.specifications ? this.goodInfo.specifications : [];
					let checkCompany = this.companyList.filter(item => item.id == record.companyId)[0];
					let {
						companyShortName,
						id
					} = checkCompany;
					this.companyInfo.companyName = companyShortName;
					// this.companyInfo.companyId = id;
				} else if (type == 'move') {
					if (from == 'personal') {
						let {
							tradeName,
							productDescription,
							productPicture,
							commoditySpecifications,
							limitBuy,
							merchantId
						} = record;
						let specifications = JSON.parse(commoditySpecifications.replace(/name/g, 'specificationName')
							.replace(/child/g, 'nextSpecifications'));
						this.goodInfo = {
							foodName: tradeName,
							foodDescription: productDescription,
							foodPic: productPicture,
							limitNum: limitBuy,
							merchantId,
							specifications,
							isUseSpecifications: specifications && specifications.length != 0 ? true : false
						};
					} else {
						this.goodInfo = record;
						this.goodInfo.isUseSpecifications = this.goodInfo.isUseSpecifications == 'yes' ? true : false;
					}
				}
				this.visiable = true;
			},
			switchChange() {
				console.log('控制了开关');
			},
			//展示下拉
			showSelect(type) {
				this.selectShow = true;
			},

			goToCropper() {
				// 此为uView的跳转方法，详见"文档-JS"部分，也可以用uni的uni.navigateTo
				uni.navigateTo({
					// 关于此路径，请见下方"注意事项"
					url: '/pages/u-avatar-cropper/u-avatar-cropper?destWidth=228&destHeight=168&rectWidth=228&rectHeight=168',
					success: res => {
						console.log('res', res);
					},
					fail: err => {
						console.log('err', err);
					}
				});
			},
			close() {
				this.clearData();
				this.$emit('hideBox');
				this.clearData();
			},
			radioChange(e) {
				this.goodInfo.isUseSpecifications = e;
			},
			//添加一级规格
			addFirstSpec() {
				let flag = false;
				this.goodInfo.specifications.forEach(item => {
					if (!item.specificationName) {
						this.$showToast.call(this, '请填写一级规格名称', 'warning');
						flag = true;
					} else {
						item.nextSpecifications.forEach(childItem => {
							if (!childItem.specificationName) {
								this.$showToast.call(this, '请填写二级规格名称', 'warning');
								flag = true;
							}
						});
					}
				});
				if (flag) {
					return;
				}
				this.$set(this.goodInfo.specifications, this.goodInfo.specifications.length, {
					specificationName: '',
					nextSpecifications: [{
						specificationName: ''
					}]
				});
			},
			//添加二级规格
			addSecoundSpec(index) {
				console.log('-----', this.goodInfo.specifications);
				let flag = false;
				console.log('+++++');
				this.goodInfo.specifications.forEach(item => {
					if (!item.specificationName) {
						this.$showToast.call(this, '请填写一级规格名称', 'warning');
						flag = true;
					}
				});
				if (flag) {
					return;
				}
				this.goodInfo.specifications[index].nextSpecifications.push({
					specificationName: ''
				});
			},
			//删除一级规格
			delFirstSpec(index) {
				this.goodInfo.specifications.splice(index, 1);
			},
			//删除二级规格
			delSecoundSpec(index, childIndex) {
				this.goodInfo.specifications[index].nextSpecifications.splice(childIndex, 1);
			},

			input(e) {
				if (this.checkPriceIndex != 999) {
					this.$showToast.call(this, '请先取消选择已选择的价格', 'warning');
					this.goodInfo.commodityPrice = '';
				}
			},

			selectCallBack(e) {
				console.log('e', e);
				this.companyInfo = this.companyList[e];
				this.companyInfo.companyName = this.companyInfo.companyShortName;
				this.goodInfo.companyId = this.companyList[e].id;
			},

			//提交信息
			async submit() {
				if (!this.goodInfo.foodName) {
					this.$showToast.call(this, '请输入商品名称', 'warning');
					return;
				}
				if (!this.goodInfo.foodPic) {
					this.$showToast.call(this, '请上传商品图片', 'warning');
					return;
				}
				if (!this.goodInfo.limitNum) {
					this.$showToast.call(this, '限购不能为空', 'warning');
					return;
				}
				if (this.goodInfo.limitNum && isNaN(Number(this.goodInfo.limitNum))) {
					this.$showToast.call(this, '限购请输入数字', 'warning');
					return;
				}
				if (this.goodInfo.limitNum && String(this.goodInfo.limitNum).split('.').length != 1) {
					this.$showToast.call(this, '限购只能为整数', 'warning');
					return;
				}
				if (this.goodInfo.limitNum < -1) {
					this.$showToast.call(this, '限购不能小于-1', 'warning');
					return;
				}
				if (this.goodInfo.sort && isNaN(Number(this.goodInfo.sort))) {
					this.$showToast.call(this, '商品排序请输入数字', 'warning');
					return;
				}
				if (this.goodInfo.sort && this.goodInfo.sort <= 0) {
					this.$showToast.call(this, '商品排序必须大于零', 'warning');
					return;
				}
				if (this.goodInfo.sort && String(this.goodInfo.sort).split('.').length != 1) {
					this.$showToast.call(this, '商品排序必须为整数', 'warning');
					return;
				}
				if (this.goodInfo.specifications) {
					let flag = false;
					this.goodInfo.specifications.forEach(item => {
						if (!item.specificationName) {
							this.$showToast.call(this, '一级规格名称不能为空', 'warning');
							flag = true;
						} else {
							item.nextSpecifications.forEach(childItem => {
								if (!childItem.specificationName) {
									this.$showToast.call(this, '二级规格名称不能为空', 'warning');
									flag = true;
								}
							});
						}
					});
					if (flag) {
						return;
					}
				}
				//如果开启了规格--必填一种规格
				if (this.goodInfo.isUseSpecifications && !this.goodInfo.specifications) {
					this.$showToast.call(this, '由于您选择了规格，请至少新增一种规格', 'warning');
					return;
				}
				if (this.goodInfo.isUseSpecifications && this.goodInfo.specifications.length == 0) {
					this.$showToast.call(this, '由于您选择了规格，请至少新增一种规格', 'warning');
					return;
				}
				let obj = JSON.parse(JSON.stringify(this.goodInfo));
				obj.merchantId = uni.getStorageSync('myInfo').id;
				if (!obj.limitNum) {
					obj.limitNum = -1;
				}
				obj.isUseSpecifications = obj.isUseSpecifications ? 'yes' : 'no';
				if (this.type == 'move') {} else {
					obj.companyId = this.companyId;
				}

				console.log('this.foodImg------', this.goodInfo.foodPic);
				if (this.goodInfo.foodPic.indexOf('://tmp') == -1 && this.goodInfo.foodPic.indexOf('wxfile:') == -1) {
					// if (this.foodImg.indexOf('data') == -1) {	// 非微信小程序
					// 复制、修改，不用上传图片，走这
					obj.foodPic = this.goodInfo.foodPic;
				} else {
					// 新增需要上传图片
					let upRes = await this.$uploadFile(this.goodInfo.foodPic);
					console.log('-----', upRes);
					let {
						success,
						message
					} = JSON.parse(upRes.data);
					obj.foodPic = message;
				}
				console.log('obj', obj);
				if (this.type == 'copy') {
					this.$delete(obj, 'id');
					if (obj.specifications) {
						for (let i = 0; i < obj.specifications.length; i++) {
							let item = obj.specifications[i];
							item.id = null;
							for (let j = 0; j < item.nextSpecifications.length; j++) {
								let childItem = item.nextSpecifications[j];
								childItem.id = null;
							}
						}
					}
				}
				if (this.type == 'move') {
					if (!this.companyInfo.companyName) {
						this.$showToast.call(this, '请选择公司', 'warning');
					}
				}
				let res = this.type != 'edit' ? await createGoodWithCompany(obj) : await editGoodWithCompany(obj);
				if (res.data.success) {
					this.$emit('showToast', this.type != 'edit' ? '添加成功' : '编辑成功', 'success');
					this.clearData();
					this.$emit('hideBox', this.type != 'edit' ? 'add' : 'edit');
				} else {
					this.$emit('showToast', res.data.message, 'warning');
				}
			},
			clearData() {
				// this.goodInfo.foodPic = '';
				this.goodInfo = {
					specifications: [],
					limitNum: '-1'
				};
				this.companyInfo = {};
				this.visiable = false;
			}
		},
		watch: {
			visiable(newVal) {
				console.log('!!!!!', newVal);
				if (!newVal) {
					this.$emit('hideBox');
					this.clearData();
				}
			}
		}
	};
</script>

<style lang="scss" scoped>
	.top {
		font-size: 28rpx;
		font-weight: bold;
		line-height: 2;
		padding: 10rpx 32rpx;
		background-color: #ff9c40;
		color: #fff;
		position: relative;
		text-align: center;

		.close-btn {
			width: 20rpx;
			height: 20rpx;
			transform: rotate(180deg);
			position: absolute;
			left: 26rpx;
			top: 32rpx;
		}
	}

	.content {
		padding: 40rpx 32rpx;

		.list {
			margin-bottom: 48rpx;

			.u-checkbox {
				margin-left: 20rpx;
			}

			/deep/.u-checkbox__icon-wrap {
				border-radius: 50%;
			}

			/deep/.u-checkbox__icon-wrap--checked {
				background-color: #fa690a !important;
				border: 1px solid #fa690a !important;
			}

			.title {
				font-size: 24rpx;
				line-height: 1;
				margin-bottom: 16rpx;
			}

			.inputContent {
				position: relative;
				background-color: #f5f5f5;
				padding-left: 20rpx;

				.arrow {
					width: 20rpx;
					height: 20rpx;
					position: absolute;
					right: 34rpx;
					top: calc((100% - 20rpx) / 2);
				}
			}

			.priceContent {
				@include flexs();
				flex-wrap: wrap;

				>view {
					font-size: 28rpx;
					line-height: 40rpx;
					padding: 20rpx 40rpx;
					background-color: #f5f5f5;
					border-radius: 12rpx;
					margin-right: 20rpx;
					margin-bottom: 10rpx;
				}

				>.checked {
					border: 1px solid #f1b825;
					color: #f1b825;
				}

				>.custom {
					width: 196rpx;
					// height: 80rpx;
					height: 35px;
					padding: 0 0;
					border-radius: 12rpx;

					/deep/.u-input__input {
						font-size: 28rpx;
						line-height: 80rpx;
						height: 80rpx;
						min-height: auto !important;
						text-align: center;
						border-radius: 12rpx;
					}
				}
			}

			.spec {
				@include flexs(space-between, center);

				>view {
					@include flexs();

					.u-radio {
						margin-left: 20rpx;
					}

					/deep/.u-radio__icon-wrap--checked {
						background-color: #fa690a !important;
						border: 1px solid #fa690a !important;
					}

					&:nth-child(2) {
						font-size: 24rpx;
						color: #fa690a;
					}
				}

				/* /deep/.u-checkbox__icon-wrap__icon {
					line-height: 5px;
				} */
			}

			.specList {
				@include flexs(space-between, center);
				margin-bottom: 20rpx;

				>view:nth-child(1) {
					width: 50%;
				}

				>view:last-child {
					@include flexs(flex-end, center);

					image {
						width: 40rpx;
						height: 40rpx;
						margin-left: 10rpx;
					}
				}
			}

			.secound {
				margin-left: 20rpx;

				>view:nth-child(1) {
					width: 70%;
					@include flexs(flex-start, center);

					>view:nth-child(1) {
						margin-right: 20rpx;
					}
				}

				>view:nth-child(2) {
					width: 20%;
				}
			}

			.stateContent {
				@include flexs();

				>view {
					font-size: 28rpx;
					height: 88rpx;
					width: 176rpx;
					border-radius: 10rpx;
					background-color: #f5f5f5;
					line-height: 88rpx;
					color: rgba(0, 0, 0, 0.55);
					text-align: center;
					margin-right: 20rpx;
				}

				>.check {
					background-color: #fff7e7;
					border: 1px solid #fa690a;
					color: #fa690a;
				}
			}

			.addImg {
				width: calc(38rpx * 8);
				height: calc(28rpx * 8);

				image {
					width: 100%;
					height: 100%;
					border-radius: 10rpx;
				}
			}
		}

		.switchList {
			@include flexs(space-between, center);

			>view:nth-child(2) {
				font-size: 0;
			}
		}

		.commenButton {
			background-color: #fa690a;
			margin-bottom: 100rpx;
		}
	}

	.selectContent {
		padding: 40rpx;

		.title {
			font-size: 32rpx;
			line-height: 2;
			font-weight: bold;
			text-align: center;
		}

		.selList {
			font-size: 28rpx;
			line-height: 40rpx;
			padding: 10rpx 0;
			border-bottom: 1px solid #eee;

			&:last-child {
				border-bottom: 0;
			}
		}
	}
</style>
<style lang="scss">
	.selectBox {
		/deep/.u-drawer-bottom {
			width: 100% !important;
			padding: 36rpx 20rpx 40rpx 20rpx;
			border-top-left-radius: 40rpx;
			border-top-right-radius: 40rpx;
			min-height: 30vh;
			max-height: 80vh !important;
			overflow-y: auto;
		}

		/deep/ {
			.u-drawer__scroll-view {
				max-height: 80vh;
			}

			.u-drawer>.u-drawer-content>.u-drawer__scroll-view>.uni-scroll-view>.uni-scroll-view {
				overflow: auto !important;
			}
		}
	}

	.addGoodBox {
		/deep/ .u-drawer {
			z-index: 100 !important;
		}
	}

	.list {
		/deep/.u-input__input {
			background-color: #f5f5f5;
			font-size: 28rpx;
			padding: 0 28rpx;
		}
	}

	.uploadContent {
		/deep/.u-list-item {
			margin-left: 0 !important;
		}
	}

	.u-switch-bak22 {
		width: 80rpx;
		height: 40rpx;

		/deep/.u-switch__node {
			width: 40rpx !important;
			height: 40rpx !important;
		}
	}
</style>